import java.io.*;
import java.lang.*;
import java.util.*;

public class FileUtil {
	private String OSName;
	
	public FileUtil() {
		OSName = System.getProperty("os.name");
	}
	
	public int mergeFile(ArrayList<String> flist, String output, String keyword) {
		// keyword: keyword in the file name, of which to be merged.

		try {
			// open an output file.
			FileWriter outWriter = new FileWriter(output);
			BufferedWriter fDesc = new BufferedWriter(outWriter);
			
			// in a loop, each iteration open a file, read data and output data to output.
			for(int i=0; i<flist.size(); i++) {
				// filter the file.
				String fName = flist.get(i);
				
				if(!fName.contains(keyword)) {
					continue;
				}
				
				// read data from the file and write the data into output file.
				FileReader inReader = new FileReader(fName);
				BufferedReader buf = new BufferedReader(inReader);
				
				String line;
				
				while((line=buf.readLine()) != null) {
					fDesc.write(line+"\n");
				}
				
				buf.close();
				inReader.close();
			}
			
			// close output file.
			fDesc.close();
			outWriter.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("files merge finished.");
		
		return 0;
	}
	
	public ArrayList<String> find(String path) {
		if(OSName.compareToIgnoreCase("Linux")!=0) {
			System.out.println("not in linux os");
		}
		
		ArrayList<String> fileList = new ArrayList<String>();
		
		try {
			String line;
			String c = "find";
			String cmd = c+" "+path;
			Process p = Runtime.getRuntime().exec(cmd);
			BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
			while((line = buf.readLine()) != null) {
				fileList.add(line);
				//System.out.println(line);	//debug
			}		
			
			buf.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return fileList;
	}
	
	public String getOSName() {
		return OSName;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String rootPath = "/home/wts/programming/workspace/edu.cmu.lti.aladdin.system/temp-uima-output/features/MoSIFT/";
		FileUtil fu = new FileUtil();
		
		//System.out.println(fu.getOSName());
		
		ArrayList<String> list = fu.find("/home/wts/programming/workspace/edu.cmu.lti.aladdin.system/temp-uima-output/features/MoSIFT/");
		System.out.println(list.size()+"items found.");
		
		for(int i=0; i<list.size(); i++) {
			System.out.println(list.get(i));	
		}
		
		System.out.println("############################################################");
		
		fu.mergeFile(list, rootPath+"merged_output.txt", "HVC");
	}

}
